//
//  YhJViewController.m
//  何五路
//
//  Created by _ADY on 15/8/7.
//  Copyright (c) 2015年 _ADY. All rights reserved.
//

#import "YhJViewController.h"

@interface YhJViewController ()

@end
static LoadingView *loading = nil;

#define Yhqhight  155/2
@implementation YhJViewController
@synthesize mTableView,dic;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = bgColor;
    self.title = @"优惠券";
    
    segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"平台优惠券",@"店铺优惠券", nil]];
    segmentedControl.frame = CGRectMake(0, 64,  screenMySize.size.width, 40);
    segmentedControl.selectedSegmentIndex = 0;
    segmentedControl.tintColor = [UIColor redColor];
    [segmentedControl addTarget:self action:@selector(segmentedSelect:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segmentedControl];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;
    
    
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40+64, screenMySize.size.width, screenMySize.size.height-40-64) style:UITableViewStyleGrouped];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.sectionHeaderHeight = 0.0;
    mTableView.sectionFooterHeight = 0.0;
    mTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mTableView];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];//清除多余分割线
    [mTableView setTableFooterView:v];
    
    
}

-(void)goloading
{
    loading = [[LoadingView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:loading];
}

- (void)segmentedSelect:(UISegmentedControl *)sender
{
    if (aOneDic.count > 0) {
        [aOneDic removeAllObjects];
        aOneDic = nil;
    }
    aOneDic = [[NSMutableArray alloc] init];
//    segmentedControl.selectedSegmentIndex = ((UISegmentedControl *)sender).selectedSegmentIndex;
    [mTableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    aOneDic = [[NSMutableArray alloc] init];
    NSLog(@"dic %@",dic);
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.delegate YhJViewArray:aOneDic];
}

#pragma mark -
#pragma mark Table View DataSource

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (segmentedControl.selectedSegmentIndex == 0)
        return 10;
    else
        return 30;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *title = nil;
    if (segmentedControl.selectedSegmentIndex == 0)
    {
        return nil;
    }
    else
    {
        title = [[[dic objectForKey:@"VendorItems"] objectAtIndex:section] objectForKey:@"VendorName"];
    }
    return title;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (segmentedControl.selectedSegmentIndex == 0)
        return 1;
    else
        return [[dic objectForKey:@"VendorItems"] count];
    
    return YES;
}

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section
{
    if (segmentedControl.selectedSegmentIndex == 0)
    {
        return [[dic objectForKey:@"PlatformCouponAppList"] count];
    }
    else
    {
        return [[[[dic objectForKey:@"VendorItems"] objectAtIndex:section] objectForKey:@"CouponAppList"] count];
    }
    
    return YES;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return Yhqhight+30;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"SettlementAllCell";
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        aTableView.showsVerticalScrollIndicator = NO;
        //        cell.tintColor = [UIColor colorWithRed:243/255.0 green:125/255.0 blue:125/255.0 alpha:1];//勾选颜色
    }
    int i = (int)[[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
        [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }
    aTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    cell.accessoryType =  UITableViewCellAccessoryNone;
    cell.backgroundColor = [UIColor whiteColor];
    NSDictionary *aDic = nil;
    if (segmentedControl.selectedSegmentIndex == 0)
        aDic =[[dic objectForKey:@"PlatformCouponAppList"] objectAtIndex:indexPath.row];
    else
        aDic = [[[[dic objectForKey:@"VendorItems"] objectAtIndex:indexPath.section] objectForKey:@"CouponAppList"] objectAtIndex:indexPath.row];
    
    
    [cell.contentView addSubview:[self setFrame:CGRectMake(10, 5, 180, 20) setTitle:[NSString stringWithFormat:@"券编号:%@",[aDic objectForKey:@"CouponCode"]] setFont:labelSize-3 setColor:[UIColor blackColor]]];

    UIImageView *bg1ImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10,25, 180,Yhqhight)];
    [bg1ImageView setImage:[UIImage imageNamed:@"image_couponaback"]];
    [cell.contentView addSubview:bg1ImageView];
    int  aOneInt = [self GOTo:NO setIndexPath:indexPath];
    if (aOneInt == 1)
    {
        [bg1ImageView setImage:[UIImage imageNamed:@"coupon_select"]];
    }
    else if (aOneInt == 2)
        [bg1ImageView setImage:[UIImage imageNamed:@"coupon_h"]];

    NSString *pricString = [NSString stringWithFormat:@"%@",[aDic objectForKey:@"CouponPrice"]];
    NSMutableAttributedString *str= [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"减¥%@满¥%@可用",pricString,[aDic objectForKey:@"UseMinPrice"]]];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 25, 170, 30)];
    titleLabel.font = [UIFont fontWithName:@"Arial" size:labelSize-3];
    titleLabel.textColor = [UIColor whiteColor];

    [str addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor]  range:NSMakeRange(2,pricString.length)];
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:labelSize+2] range:NSMakeRange(2,pricString.length)];
    titleLabel.attributedText = str;
    [cell.contentView addSubview:titleLabel];
    
    NSString *useTypeStr = nil;
    if ([[NSString stringWithFormat:@"%@",[aDic objectForKey:@"UseType"]] isEqualToString:@"1"]) {
        useTypeStr = @"使用条件:满减";
    }
    else
         useTypeStr = @"使用条件:每满减";
    [cell.contentView addSubview:[self setFrame:CGRectMake(20, 55, 170, 10) setTitle:useTypeStr setFont:labelSize-3 setColor:[UIColor whiteColor]]];

    NSString * StartTime = [aDic objectForKey:@"StartDate"];
    NSString * endTime = [aDic objectForKey:@"EndDate"];
    StartTime =  [StartTime stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    StartTime =  [StartTime stringByReplacingOccurrencesOfString:@"00:00:00" withString:@""];
    StartTime =  [StartTime stringByReplacingOccurrencesOfString:@"+08:00" withString:@" "];
    endTime =  [endTime stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    endTime =  [endTime stringByReplacingOccurrencesOfString:@"00:00:00" withString:@""];
    endTime =  [endTime stringByReplacingOccurrencesOfString:@"+08:00" withString:@" "];
    
    [cell.contentView addSubview:[self setFrame:CGRectMake(20, 70, 170, 30) setTitle:[NSString stringWithFormat:@"有效时间:%@－%@",StartTime,endTime] setFont:labelSize-3 setColor:[UIColor whiteColor]]];
    
    [cell.contentView addSubview:[self setFrame:CGRectMake(200, 25, 100, 50) setTitle:[NSString stringWithFormat:@"-全品类(特例商品除外)\n-可在 全平台 使用"] setFont:labelSize-3 setColor:[UIColor blackColor]]];
    
    
    NSString *CouponStr = nil;
    if ([[NSString stringWithFormat:@"%@",[aDic objectForKey:@"CouponLevel"]] isEqualToString:@"1"]) {
        CouponStr = @"平台优惠券";
    }
    else if ([[NSString stringWithFormat:@"%@",[aDic objectForKey:@"CouponLevel"]] isEqualToString:@"2"])
        CouponStr = @"店铺优惠券";
    else
        CouponStr = @"单品优惠券";
    [cell.contentView addSubview:[self setFrame:CGRectMake(200, Yhqhight+10, 100, 20) setTitle:[NSString stringWithFormat:@"来源:%@",CouponStr] setFont:labelSize-3 setColor:[UIColor blackColor]]];
    
    // Configure the cell...
    return cell;
}

-(UILabel*)setFrame:(CGRect)frame setTitle:(NSString*)title setFont:(int)font setColor:(UIColor*)myColor
{
    title = [title stringByReplacingOccurrencesOfString:@"<null>" withString:@""];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:frame];
    if (title != nil)
        titleLabel.text = [NSString stringWithFormat:@"%@",title];
    titleLabel.textAlignment = 0;
    titleLabel.numberOfLines = 0;
    titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:font];
    titleLabel.textColor = myColor;
    return titleLabel;
}

-(int)GOTo:(BOOL)mBOOL setIndexPath:(NSIndexPath *)indexPath
{
    int GetInt = 0;// 0可选 1已选  2灰选
    if ([aOneDic count] <= indexPath.section)
    {
        if ([aOneDic count] == 0)
        {
            for (int i = 0; i <= indexPath.section; i++)
            {
                NSMutableDictionary *aDadic = [NSMutableDictionary dictionaryWithCapacity:10];
                [aDadic setObject:@"1" forKey:@"aKey"];
                [aOneDic insertObject:aDadic atIndex:i];
            }
        }
        else
        {
            NSMutableDictionary *aDadic = [NSMutableDictionary dictionaryWithCapacity:10];
            [aDadic setObject:@"1" forKey:@"aKey"];
            [aOneDic insertObject:aDadic atIndex:indexPath.section];
        } 
    }
    
    NSMutableDictionary *aDic = nil;
    if (segmentedControl.selectedSegmentIndex == 0)
    {
        aDic =[[dic objectForKey:@"PlatformCouponAppList"] objectAtIndex:indexPath.row];
    }
    else
        aDic = [[[[dic objectForKey:@"VendorItems"] objectAtIndex:indexPath.section] objectForKey:@"CouponAppList"] objectAtIndex:indexPath.row];
    
    if (mBOOL)
    {
        if ([[[aOneDic objectAtIndex:indexPath.section] allKeys] containsObject:[NSString stringWithFormat:@"Select%d",indexPath.row]])//取消选择
        {
            NSString *idOneStr = [NSString stringWithFormat:@"%@",[[aOneDic objectAtIndex:indexPath.section] objectForKey:@"Id"]];
            NSArray *idArray = [idOneStr componentsSeparatedByString:@","];
            if (idArray.count == 1)//取消最后一个选择
            {
                [[aOneDic objectAtIndex:indexPath.section] removeAllObjects];
                
                NSMutableDictionary *aDadic = [NSMutableDictionary dictionaryWithCapacity:10];
                [aDadic setObject:@"1" forKey:@"aKey"];
                [aOneDic insertObject:aDadic atIndex:indexPath.section];
            }
            else
            {
                idOneStr = [idOneStr stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@",[aDic objectForKey:@"Id"]] withString:@""];
                idOneStr = [idOneStr stringByReplacingOccurrencesOfString:@",," withString:@","];
                if([[idOneStr substringFromIndex:idOneStr.length-1] hasPrefix:@","])
                {
                    idOneStr = [idOneStr substringToIndex:idOneStr.length-1];
                    
                }
                if([[idOneStr substringToIndex:1] hasSuffix:@","])
                {
                    idOneStr = [idOneStr substringFromIndex:1];
                }
                NSLog(@"idOneStr %@",idOneStr);
                [[aOneDic objectAtIndex:indexPath.section] setObject:idOneStr forKey:@"Id"];
                
                NSString *PriceStr = [NSString stringWithFormat:@"%f",[[[aOneDic objectAtIndex:indexPath.section] objectForKey:@"CouponPrice"]floatValue]-[[aDic objectForKey:@"CouponPrice"] floatValue]];
                [[aOneDic objectAtIndex:indexPath.section] setObject:PriceStr forKey:@"CouponPrice"];
            }
        }
        else
        {
            if ([[[aOneDic objectAtIndex:indexPath.section] allKeys] containsObject:@"RuleId"])//已有选择
            {
                if ([[NSString stringWithFormat:@"%@",[[aOneDic objectAtIndex:indexPath.section] objectForKey:@"UseType"]] isEqualToString:@"2"])//2每满减   1满减返回无法点击
                {
                    if ([[NSString stringWithFormat:@"%@",[[aOneDic objectAtIndex:indexPath.section] objectForKey:@"RuleId"]] isEqualToString:[aDic objectForKey:@"RuleId"]])//价格是否超出
                    {
                        NSString *idOneStr = [NSString stringWithFormat:@"%@,%@",[[aOneDic objectAtIndex:indexPath.section] objectForKey:@"Id"],[aDic objectForKey:@"Id"]];
                        [[aOneDic objectAtIndex:indexPath.section] setObject:idOneStr forKey:@"Id"];
                        NSString *PriceStr = [NSString stringWithFormat:@"%f",[[[aOneDic objectAtIndex:indexPath.section] objectForKey:@"CouponPrice"]floatValue]+[[aDic objectForKey:@"CouponPrice"] floatValue]];
                        [[aOneDic objectAtIndex:indexPath.section] setObject:PriceStr forKey:@"CouponPrice"];
                    }
                }
            }
            else//第一个选择
            {
                NSLog(@"aDic %@",aDic);
                [[aOneDic objectAtIndex:indexPath.section] setObject:[aDic objectForKey:@"RuleId"] forKey:@"RuleId"];
                [[aOneDic objectAtIndex:indexPath.section] setObject:[aDic objectForKey:@"CouponLevel"] forKey:@"CouponLevel"];
                [[aOneDic objectAtIndex:indexPath.section] setObject:[aDic objectForKey:@"UseType"] forKey:@"UseType"];
                [[aOneDic objectAtIndex:indexPath.section] setObject:[aDic objectForKey:@"VendorId"] forKey:@"VendorId"];
                [[aOneDic objectAtIndex:indexPath.section] setObject:[aDic objectForKey:@"CouponPrice"] forKey:@"CouponPrice"];
                [[aOneDic objectAtIndex:indexPath.section] setObject:[aDic objectForKey:@"Id"] forKey:@"Id"];
                [[aOneDic objectAtIndex:indexPath.section] setObject:@"1" forKey:[NSString stringWithFormat:@"Select%d",indexPath.row]];
            }
        }
            
    }
    else
    {
        if ([[[aOneDic objectAtIndex:indexPath.section] allKeys] containsObject:[NSString stringWithFormat:@"Select%d",indexPath.row]])
                GetInt = 1;
        else
        {
            if ([[[aOneDic objectAtIndex:indexPath.section] allKeys] containsObject:@"RuleId"])//已有选择
            {
                if ([[NSString stringWithFormat:@"%@",[[aOneDic objectAtIndex:indexPath.section] objectForKey:@"UseType"]] isEqualToString:@"2"])//2每满减   1满减返回无法点击
                {
                     if ([[NSString stringWithFormat:@"%@",[[aOneDic objectAtIndex:indexPath.section] objectForKey:@"RuleId"]] isEqualToString:[aDic objectForKey:@"RuleId"]])
                         GetInt = 0;
                }
                else
                    GetInt = 2;
            }
            else
            {
                GetInt = 0;
            }
        }
    }
    
    return GetInt;
}

- (void)tableView:(UITableView *)table1View didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self GOTo:YES setIndexPath:indexPath];
    [mTableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
